package warehouse;

import java.sql.*;

public class OrderBean {
	
	public static boolean addOrder(int clientNo,Date orderDate,int[] cargoNoList,int[] purchaseNumList) {
		Connection connection = DatabaseBean.connect();
		try {
			

			//添加新订单
			String sql = "INSERT INTO orders(orderDate,clientNo) VALUES(?,?);";
			
			PreparedStatement ps=connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			
			ps.setDate(1, orderDate);
			ps.setInt(2, clientNo);
			ps.executeUpdate();
			ResultSet rs = ps.getGeneratedKeys();//获取自增主键
			int orderNo=0;//保存生成的订单编号
			if (rs != null&&rs.next()) {  
				orderNo=rs.getInt(1); 
			}
			//System.out.println("生成的订单号为："+orderNo);//测试语句

			//插入到货物-订单表
			sql = "INSERT INTO cargo_order(cargoNo,orderNo,purchaseNum) VALUES(?,?,?);";
			
			PreparedStatement ps2 = connection.prepareStatement(sql);
			for(int i=0;i<cargoNoList.length;i++) {
				ps2.setInt(1, cargoNoList[i]);
				ps2.setInt(2, orderNo);
				ps2.setInt(3, purchaseNumList[i]);
				ps2.executeUpdate();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}finally {
			if(connection!=null) {
				try {
					connection.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}
}
